import time, datetime

irc = None

users = {}

def init(bot):
    global irc

    irc = bot
    irc.cmd.events['PRIVMSG'].subscribe(handle_privmsg)
    irc.cmd.events['JOIN'].subscribe(handle_join)
    irc.cmd.events['PART'].subscribe(handle_part)
    irc.cmd.events['KICK'].subscribe(handle_kick)
    irc.cmd.events['QUIT'].subscribe(handle_quit)


def handle_privmsg(sender, args):
    global irc
    global users

    channel = args[2]
    msg = args[0].split()

    if msg[0] == '!seen':
        u = msg[1]
        if u in users.keys():
            t = users[u][1]
            d = datetime.fromtimestamp(t)
                        
            irc.privmsg(channel, 
                    "%s, the last time I saw %s was %s." % (sender.nick, u,
                        d.strftime("%b %d, %Y %H:%M %Z")))
        else:
            ch = irc.chmgr.get(channel)
            if u in ch.users:
                irc.privmsg(channel, 
                    "%s, %s is here right now!" % (sender.nick, u))
            else:
                irc.privmsg(channel,
                    "Sorry, %s. I haven't seen %s before." % (sender.nick, u))

def handle_part(sender, args):
    global irc
    global users

    if sender.nick != irc.nickname:
        users[sender.nick] = ('part', time.time(), args)

def handle_kick(sender, args):
    global irc
    global users

    if args[3] != irc.nickname:
        users[args[3]] = ('kick', time.time(), args)

def handle_quit(sender, args):
    global users
    if sender.nick != irc.nickname:
        users[sender.nick] = ('quit', time.time(), args)

def handle_join(sender, args):
    global users
    if sender.nick != irc.nickname and sender.nick in users.keys():
        del users[sender.nick]
